//
//  FTextArea.swift
//  takeaway
//
//  Created by zhuxietong on 2021/2/20.
//

import Foundation
import Eelay

open class FTextArea:FField,UITextViewDelegate{
    public let wordCountL = ASButtonNode()
    public let backNode = MoDisplayNode()

    public let textNode = ASDisplayNode { () -> UIView in
        
    
        let textArea = NextGrowingInternalTextView()
        textArea.font = .systemFont(ofSize: 14)
        textArea.textAlignment = .left
        textArea.textColor = ._foreground
        textArea.returnKeyType = .done
        return textArea
    }
    
    public var height:CGFloat = 80
   
    deinit {
//        textView.removeObserver(self, forKeyPath: "text")
    }
        open func checkWordCount(){
        

        let max = self.props.num_limit.max
        if max > 100000{
            wordCountL.alpha = 0
            return
        }
        
        let text = textView.text ?? ""

        self.wordCountL.ui.ntitle(title: "\(Int(text.count))/\(max)")
        wordCountL.backgroundColor = UIColor(shex: "#888").alpha(0.1)
 
    }

    public var textView:UITextView{
        return (textNode.view as? UITextView) ?? UITextView()
    }
    open override func didLoadProps() {
        textView.text = "\(value)"
       
        lableNode.attributedText = _lable
        textView.attributedPlaceholder = placeholder.ui.font(font: placeHolderStyle.font).color(color: placeHolderStyle.color).left.astring
        checkWordCount()
    }
    
    open override func update(value:Any,edit:FEdit){
        self.value = value
        switch edit {
        case .input:
            break
        case .reply:
            didLoadProps()
            updateDispaly()
        default:
            didLoadProps()
            updateDispaly()
        }
    }
    
    open override func addLayoutRules() {
        super.addLayoutRules()
        wordCountL.ui.ncolor(color: ._weak).font(size: 12).padding(insets: [3,4]).set(radius: 8, width: nil, color: nil)
        backNode.bsui.background(color: ._tableBackground).set(radius: 6, width: TP.separatorHeight, color: ._separator)
    }
  
    open override func willLayoutRules() {
        super.willLayoutRules()
        textView.delegate = self
        textNode.backgroundColor = .clear
        
//        textNode.bsui.background(color: ._tableBackground).set(radius: 3, width: 1, color: UIColor._separator.alpha(0.3))
//        textView.addObserver(self, forKeyPath: "text", options: [.new,.old], context: nil)

    }
    
    open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        if text == "\n"{
            textView.resignFirstResponder()
            return false
        }
        let newStr = textView.text + text
        if newStr.len > maxWordCount{
            return false
        }

        return true
        
    }
    
    open var maxWordCount:Int{
        return props.num_limit.max
    }
    
    open func textViewDidChange(_ textView: UITextView) {

        if textView.text.count > maxWordCount {

            //获得已输出字数与正输入字母数
            let selectRange = textView.markedTextRange

            //获取高亮部分 － 如果有联想词则解包成功
            if let selectRange = selectRange {
                let position =  textView.position(from: (selectRange.start), offset: 0)
                if (position != nil) {
                    return
                }
            }

            guard let textContent = textView.text else {
                return
            }

            //截取200个字
            if textContent.len > maxWordCount {
//                let index = textContent.index((textContent.startIndex)!, offsetBy: maxWordCount)
                let str = textContent.sub(from: 0, end: (maxWordCount - 1))
                textView.text = str
            }
        }
        update(value: textView.text ?? "", edit: .input)

        checkWordCount()

   }

    
    

//    open override func specGetter() -> _Spec {
//        return .stack(["v|8",&-.stretch,_nowrap], childs: [
//            lableNode.Spec,
//            textNode["\(height)"]
//        ])
//    }
    
    open override func specGetter() -> _Spec {
        let spec = _Spec.inset([], [0], child: .stack(["v|3",&-.stretch], childs: [
            textNode["\(height)"].addOver(.stack(["v",&-.stretch,_justfy(.space_between)], childs: [
                .stack([], childs: []),
                .stack(["h",_justfy(.space_between)], childs: [
                    .stack([], childs: []),
                    _Spec.inset([], [4], child: wordCountL.Spec)
                ])
            ]))
        ])).addBack(backNode.Spec)
        return .stack(["v|8",&-.stretch], childs: [
            .if(label.len > 0, spec: lableNode.Spec),
            spec
        ])
    }
}
